package controllers

import (
	"finance/internal/dto"
	"finance/internal/message"
	"finance/internal/models"
	"finance/internal/services"
	"finance/internal/utils"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// GetMyAccount @Summary Get Account
// @Description 获取个人账户信息
// @Tags account
// @Produce json
// @Param Token header string true "Login token"
// @Success 200 {object} dto.AccountResponse
// @Failure 400 {object} utils.Response
// @Router /account/getInfo [GET]
func GetMyAccount(c *gin.Context) {
	userID := c.GetUint("userID")

	info, err := services.GetUserAccountInfo(userID)
	if err != nil {
		utils.Fail(c, 400, "Account not found")
		return
	}

	utils.Success(c, info)
}

// GetAllAccounts @Summary Get All Accounts
// @Description 获取所有账户信息
// @Tags account
// @Produce json
// @Param Token header string true "Login token"
// @Success 200 {object} []dto.AccountResponse
// @Failure 400 {object} utils.Response
// @Router /account/getAccounts [GET]
func GetAllAccounts(c *gin.Context) {
	accounts, err := services.GetAllAccounts()
	if err != nil {
		utils.Fail(c, 500, "Failed to get accounts")
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
		"data": accounts,
	})
}

// CreateAccount @Summary Create Account
// @Description 创建账户（初次开户自动生成初始密码123456，用户名需唯一）
// @Tags account
// @Accept json
// @Produce json
// @Param req body dto.CreateAccountRequest true "创建账户请求参数"
// @Success 200 {object} utils.Response
// @Failure 400 {object} utils.Response "请求参数错误"
// @Failure 500 {object} utils.Response "服务器内部错误"
// @Router /account/create [POST]
func CreateAccount(c *gin.Context) {
	var req dto.CreateAccountRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "Invalid request",
		})
		return
	}

	user, err := models.GetUserByUsername(req.Username)
	if err != nil {
		user = &models.User{
			Username: req.Username,
			Password: "123456", // 初次开户时的初始化密码
		}
		if err := models.CreateUser(user); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"msg": "failed to create user",
			})
		}
		return
	}

	account := models.Account{
		OwnerUserID: user.ID,
		Balance:     req.InitialBalance,
		Status:      "active",
	}

	if err := models.CreateAccount(&account); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"msg": "failed to create account",
		})
	}

	c.JSON(http.StatusOK, gin.H{
		"msg":     "Account created",
		"user":    user.Username,
		"account": account,
	})
}

// DisableAccount @Summary Disable Account
// @Description 禁用指定ID的账户（通过路径参数传递账户ID）
// @Tags account
// @Produce json
// @Param id path uint64 true "账户ID（需禁用的账户唯一标识）"
// @Param Token header string true "登录令牌（权限验证）"
// @Success 200 {object} utils.Response
// @Failure 400 {object} utils.Response
// @Router /account/disable/{id} [PUT]
func DisableAccount(c *gin.Context) {
	role, _ := c.Get("role")
	if role != "branch_admin" {
		c.JSON(http.StatusBadRequest, gin.H{
			"msg": "Access denied: only branch admin can disable account",
		})
	}

	accountIDParam := c.Param("id") // get target accountID from path
	accountID, err := strconv.Atoi(accountIDParam)
	if err != nil || accountID <= 0 {
		utils.Fail(c, http.StatusBadRequest, message.InvalidAccountID)
		return
	}

	err = services.DisableAccount(uint(accountID))
	if err != nil {
		utils.Fail(c, http.StatusInternalServerError, message.AccountDisableFailed)
		return
	}

	utils.Success(c, message.AccountDisabled)

}
